package com.talking.service;

import com.talking.controller.ReceiveThread;
import com.talking.pojo.*;
import com.talking.tools.ThreadPool;

import java.io.ObjectOutputStream;
import java.util.List;

public class NoticeService {
    private GroupService groupService;
    private  RelationService relationService;
    private  UserService userService;
    private ObjectOutputStream out;

    public NoticeService(ObjectOutputStream out){
        groupService = new GroupService();
        relationService = new RelationService();
        userService = new UserService();
        this.out = out;

    }

    //添加好友
    public void addFriend(Notice notice){
        User sender = notice.getSender();
        User receiver = notice.getReceiver().get(0);

        int count = relationService.getUserRelation(sender.getUser_id(),receiver.getUser_id(),1);
        if (count==0){
            int count1 = relationService.insertUserRelationService(sender.getUser_id(),receiver.getUser_id(),true);
        try {
            if (count1 == 1) {
                //返回好友列表
                Message outMSG = new Message();
                outMSG.setMessageType(MessageType.ADD_FRIEND);
                outMSG.setContent(new UserService().getFriendListService(sender.getUser_id()));
                out.writeObject(outMSG);

                ReceiveThread thread = ThreadPool.getThread(receiver.getUser_id());
                if (thread != null) {
                    ObjectOutputStream out1 = thread.getOut();
                    outMSG.setContent(new UserService().getFriendListService(receiver.getUser_id()));
                    out1.writeObject(outMSG);
                }
            }
        }catch (Exception e){e.printStackTrace();}
        }


    }

    //加入群聊
    public void joinGroup(Notice notice){
        User user = notice.getSender();
        Group group = notice.getGroup();
        int userID = user.getUser_id();
        int groupID = group.getGroup_id();

        int count = relationService.getUserRelation(userID,groupID,0);

        try {
            if (count == 0) {
                int count1 = relationService.insertUserRelationService(userID, groupID, false);
                if (count1 == 1) {
                    Group tempGroup = groupService.getSignGroup(String.valueOf(groupID));
                    group.setCount_user(tempGroup.getCount_user() + 1);
                    int temp = groupService.updateGroupMess(group);
                    if (temp == 1) {
                        Message outMSG = new Message();
                        outMSG.setMessageType(MessageType.UPDATE_GROUP_LIST);
                        outMSG.setContent(groupService.getUserGroup(userID));
                        outMSG.setResponseType(true);
                        out.writeObject(outMSG);
                    }
                }
            }
        }catch (Exception e){e.printStackTrace();}
    }
}
